package com.ohc.leetcode.二叉树;

import com.ohc.leetcode.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 2022年5月3日09:58:43
 */
public class 完全二叉树的节点个数222 {
    public static int countNodes1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int len = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
//            TreeNode node = queue.poll();    // 把poll放在这里，会循环两次。就是size=2 但是node结点为同一个
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
                len++;
            }
        }
        return len;
    }

    /**
     * 递归暴力
     *
     * @param root
     * @return
     */

    public static int countNodes2(TreeNode root) {
        if (root == null) { // 终止条件
            return 0;
        }
        int left = 0;
        int right = 0;
        if (root.left != null) {
            left = countNodes2(root.left);
        }
        if (root.right != null) {
            right = countNodes2(root.right);
        }
        return left + right + 1;
    }

    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode();
        TreeNode treeNode2 = new TreeNode();
        TreeNode treeNode3 = new TreeNode();
        treeNode1.right = treeNode2;
        treeNode1.left = treeNode3;
        treeNode2.right = null;
        treeNode2.left = null;
        treeNode3.right = null;
        treeNode3.left = null;
        treeNode1.val = 1;
        treeNode2.val = 2;
        treeNode3.val = 3;
        int nodes = countNodes1(treeNode1);
        System.out.println("nodes = " + nodes);
    }
}
